package org.atlantis.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FastFileCopier {

	public static void main(String[] args) throws Exception {
		File in = new File("E:/downloads/others/Office.2007.简体中文正式版.(大企业版).img");
		File out = new File("F:/Office.2007.简体中文正式版.(大企业版).img");
		long startTime = System.currentTimeMillis();
		copy(in, out);
		long endTime = System.currentTimeMillis();
		System.out.println("Copy waste time: " + (endTime - startTime) + " ms.");
	}

	private static void copy(File in, File out) throws IOException {
		FileChannel inChannel = new FileInputStream(in).getChannel();
		FileChannel outChannel = new FileOutputStream(out).getChannel();

		// 最快的方式：但是当文件很大时就会出现错误
		// inChannel.transferTo(0, inChannel.size(), outChannel);

		try {
			// 一次传输256MB的内容
			int maxCount = (256 * 1024 * 1024);
			long size = inChannel.size();
			long position = 0;
			while (position < size) {
				position += inChannel.transferTo(position, maxCount, outChannel);
			}
		} finally {
			if (inChannel != null) inChannel.close();
			if (outChannel != null) outChannel.close();
		}
	}
}
